<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />

    <base-table-card>
      <template #header-right>
        <el-button v-auth="[PERMS.GOODS.CATEGORY.ADD]" type="primary" @click="onAddRoot">新增一级类目</el-button>
      </template>

      <avue-crud
        ref="crudRef"
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <!-- 上级类目（表单显示值） -->
        <template #name="{ row }">
          <div class="icon-container">
            <div
              class="icon-container-expand"
              v-if="row.parentId === 0 && (!row.children || !row.children.length)"
            ></div>
            <span>{{ row.name }}</span>
          </div>
        </template>

        <!-- 展示状态开关：用 @change，避免刷新时误触发 -->
        <template #categoryStatus="{ row }">
          <el-tag type="success" v-if="row.categoryStatus === 1">已启用</el-tag>
          <el-tag type="info" v-else>已停用</el-tag>
        </template>

        <!-- 操作列 -->
        <template #menu="{ row }">
          <!-- 启用：1  停用：0-->
          <el-button
            v-auth="[PERMS.GOODS.CATEGORY.ENABLE]"
            type="primary"
            text
            @click="handleToggleDisplay(row)"
            v-if="row.categoryStatus === 1"
            >停用</el-button
          >
          <el-button v-auth="[PERMS.GOODS.CATEGORY.ENABLE]" type="primary" text @click="handleToggleDisplay(row)" v-else
            >启用</el-button
          >
          <!-- 编辑 -->
          <el-button v-auth="[PERMS.GOODS.CATEGORY.UPDATE]" type="primary" text @click="handleEdit(row)"
            >编辑</el-button
          >

          <!-- 只有一级才能“加下级”（第二级不显示） -->
          <el-button
            v-auth="[PERMS.GOODS.CATEGORY.ADD_NEXT]"
            v-if="canAddChild(row)"
            type="primary"
            text
            @click="onAddChild(row)"
          >
            加下级
          </el-button>

          <!-- 删除：不可删时禁用 + 提示，可删时可点 -->
          <template v-if="!canDelete(row)">
            <el-tooltip :content="deleteTip(row)" placement="top">
              <span>
                <el-button text disabled>删除</el-button>
              </span>
            </el-tooltip>
          </template>
          <el-button v-auth="[PERMS.GOODS.CATEGORY.DELETE]" v-else type="danger" text @click="loadDel(row)">
            删除
          </el-button>
        </template>
      </avue-crud>
    </base-table-card>
  </base-container>
</template>

<script setup>
  import Option from "@/crudOption/goods/category";
  import { ElMessageBox } from "element-plus";

  /* ================== CRUD Hook ================== */
  let {
    data: tableData,
    loading: tableLoading,
    page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    del: loadDel,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.goods.categoryList,
    add: Api.goods.categoryAdd,
    edit: Api.goods.categoryUpdate,
    del: Api.goods.categoryDelete,
    dataRes: "data.records", // 返回 data 为数组
    // 搜索参数格式化
    getParamsFormat: p => {
      const params = { ...p };
      if (Array.isArray(params.createTime) && params.createTime.length === 2) {
        params.createBeginTime = `${params.createTime[0]} 00:00:00`;
        params.createEndTime = `${params.createTime[1]} 23:59:59`;
      }
      if (Array.isArray(params.updateTime) && params.updateTime.length === 2) {
        params.updateBeginTime = `${params.updateTime[0]} 00:00:00`;
        params.updateEndTime = `${params.updateTime[1]} 23:59:59`;
      }
      if (params.categoryStatus === "") delete params.categoryStatus; // 空值不传
      delete params.createTime;
      delete params.updateTime;
      return params;
    },

    // 新增参数格式化
    addParamsFormat: row => ({
      ...row,
      applicableObjects: Array.isArray(row.applicableObjects)
        ? row.applicableObjects.join(",")
        : row.applicableObjects || "",
      categoryStatus: Number(row.categoryStatus ?? 1),
      sortNo: Number(row.sortNo ?? 1),
      platform: 1,
      categoryType: row.parentId ? 2 : 1,
    }),

    // 编辑参数格式化
    editParamsFormat: row => ({
      ...row,
      applicableObjects: Array.isArray(row.applicableObjects)
        ? row.applicableObjects.join(",")
        : row.applicableObjects || "",
      categoryStatus: Number(row.categoryStatus ?? 1),
      sortNo: Number(row.sortNo ?? 1),
    }),
  });

  // 配置
  const { searchOption, tableOption } = Option();

  /* ================== 基础引用 ================== */
  const crudRef = ref(null);

  /* ================== 新增/编辑 ================== */
  // 新增根级
  function onAddRoot() {
    formData.value.parentId = 0;
    formData.value.parentName = "主类目";
    crudRef.value?.rowAdd();
  }

  // 在某行下新增
  function onAddChild(row) {
    formData.value.parentId = row.id;
    formData.value.parentName = row.name;
    crudRef.value?.rowAdd();
  }

  // 编辑（补 parentName & applicableObjects 数组）
  function handleEdit(row) {
    const parentName = findParentName(tableData.value, row.parentId) || "主类目";
    crudRef.value?.rowEdit({
      ...row,
      parentName,
      applicableObjects: (row.applicableObjects || "").split(",").filter(Boolean),
    });
  }

  // 递归找父级名称
  function findParentName(list, pid) {
    if (!pid) return "";
    for (const n of list || []) {
      if (n.id === pid) return n.name;
      const hit = findParentName(n.children, pid);
      if (hit) return hit;
    }
    return "";
  }

  /* ================== 层级标注（不依赖后端 _level） ================== */
  const levelMap = ref(new Map());

  function markLevels(list, level = 1) {
    if (!Array.isArray(list)) return;
    for (const node of list) {
      levelMap.value.set(node.id, level);
      node._level = level; // 方便调试/查看
      if (Array.isArray(node.children) && node.children.length) {
        markLevels(node.children, level + 1);
      }
    }
  }

  watch(
    tableData, // 直接传 ref
    val => {
      levelMap.value = new Map();
      markLevels(Array.isArray(val) ? val : [], 1);
    },
    { immediate: true }
  );

  /* ================== 操作列规则 ================== */
  const hasChildren = row => Array.isArray(row?.children) && row.children.length > 0;

  // 只有一级/二级可“加下级”
  const canAddChild = row => (levelMap.value.get(row.id) ?? 1) < 2;

  // 删除可用性与提示
  const canDelete = row => row.categoryStatus != 1;
  const deleteTip = row => {
    if (row.categoryStatus == 1) return "该类目已启用，等停用后再删除";
    return "";
  };

  /* ================== 展示状态开关（确认 + loading） ================== */
  async function handleToggleDisplay(row) {
    const nextVal = row.categoryStatus === 1 ? 0 : 1;
    const msg = nextVal === 0 ? "确定要隐藏该类目吗？隐藏后前台不可见。" : "确定要展示该类目吗？展示后前台可见。";

    try {
      await ElMessageBox.confirm(msg, "提示", { type: "warning" });
      row._statusLoading = true;
      await Api.goods.categoryChangeStatus({ id: row.id, categoryStatus: nextVal });
      // row.categoryStatus = nextVal; // 手动切换
      loadGetTableData();
      $msg.success(nextVal ? "已展示" : "已隐藏");
    } finally {
      row._statusLoading = false;
    }
  }

  /* ================== 挂载 ================== */
  onMounted(() => {
    loadGetTableData();
  });
</script>

<style lang="scss" scoped>
  // 选择表格第一列的所有单元格 (td)
  :deep(.el-table__row td:first-child) {
    // 展开图标处理
    .cell {
      display: flex;
      flex-wrap: nowrap;
      align-items: center;

      .icon-container {
        display: flex;
        flex-wrap: nowrap;
        align-items: center;

        .icon-container-expand {
          width: 16px;
          height: 16px;
          margin-right: 16px;
        }
      }

      // 解决二级路由，文字对齐问题
      .el-table__placeholder {
        margin-right: 12px;
      }

      // 自定义展开图标（未展开）
      .el-table__expand-icon {
        position: relative;
        display: block;
        width: 16px;
        height: 16px;
        margin-right: 16px;
        font-family: var(--iconfont-family);

        .el-icon {
          display: none;
        }

        &::before {
          content: "\e82f";
          width: 12px;
          height: 12px;
          display: flex;
          justify-content: center;
          align-items: center;
          padding: 1px;
          border: 1px solid var(--cb1);
          background-color: var(--fl1);
          border-radius: 2px;
        }
      }

      // 自定义展开图标（已展开）
      .el-table__expand-icon--expanded {
        transform: rotate(90deg);

        &::before {
          content: "\e830";
          transform: rotate(-90deg);
        }
      }
    }
  }
</style>
